﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using ERPStore.Web.Extensions;

namespace ERPStore.Web.Events
{
	public class TrackerEvent : ERPStore.Events.TrackerEvent
	{
		public TrackerEvent(HttpContextBase ctx, ViewResult viewResult)
			: base()
		{
			UserHostAddress = ctx.Request.UserHostAddress;
			UserAgent = ctx.Request.UserAgent;
			bool exist =false;
			VisitorId = ctx.GetOrCreateVisitorId(out exist);
			RawUrl = ctx.Request.RawUrl;
			Referer = (ctx.Request.UrlReferrer != null) ? ctx.Request.UrlReferrer.OriginalString : string.Empty;
			LocalPath = ctx.Request.Url.LocalPath;
			ResponseStatusCode = ctx.Response.StatusCode;
			if (ctx.Request.UserLanguages != null
				&& ctx.Request.UserLanguages.Length > 0)
			{
				Language = ctx.Request.UserLanguages[0];
			}
			OriginalUrl = ctx.Request.Url.OriginalString;
			if (viewResult != null)
			{
				foreach (var item in viewResult.ViewData.Keys)
				{
					var value = viewResult.ViewData[item];
					if (value != null)
					{
						ExtendedParameters.Add("ViewDataItem:" + item, value.ToString());
					}
				}
			}
			foreach (var item in ctx.Items.Keys)
			{
				var value = ctx.Items[item];
				if (value != null)
				{
					var key = item.ToString();
					if (!ExtendedParameters.ContainsKey(key))
					{
						ExtendedParameters.Add(key, value.ToString());
					}
				}
			}

			if (ctx.Request.Form != null)
			{
				foreach (var item in ctx.Request.Form.AllKeys)
				{
					ExtendedParameters.Add("FormPost:" + item, ctx.Request.Form[item]);
				}
			}
			if (viewResult != null)
			{
				ViewName = viewResult.ViewName;
			}

			if (ctx.User.Identity.IsAuthenticated)
			{
				if (ctx.User is ERPStore.Models.UserPrincipal)
				{
					UserId = ((ERPStore.Models.UserPrincipal)ctx.User).CurrentUser.Id;
				}
			}
		}

		public TrackerEvent(HttpContextBase ctx, ViewResult viewResult, RouteData routeData)
			: this(ctx, viewResult)
		{
			ControllerName = routeData.Values["controller"] as string;
			ActionName = routeData.Values["actionName"] as string;
		}

	}
}
